package com.bigtotoro.shuiyincamera.image;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.editimage.utils.BitmapUtils;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.bigtotoro.shuiyincamera.video.view.CropImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;
import qiu.niorgai.StatusBarCompat;

/**
 * 图片去水印
 */
public class RemoveWaterMark2Activity extends AppCompatActivity implements View.OnClickListener {
    public static final String TAG = "image-remove-water";
    public static final String EXTRA_OUTPUT = "extra_output";

    private RelativeLayout iRoot;
    private FrameLayout frameLayout;
    private ImageView imageView;
    private CropImageView cropView;
    private int imageWidth, imageHeight;//
    private int rootWidth, rootHeight;//
    private String path;//从相册返回的原始图片存储地址
    private float scale;


    private String outPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remove_water_mark);

        //添加友盟事件统计
        MyUtils.addUmengEvent(RemoveWaterMark2Activity.this,"img_remove_water","图片去水印");

        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.black));
        initView();
    }

    private void initView() {
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.btn_save).setOnClickListener(this);

        path = getIntent().getStringExtra("path");//图片原始路径
        imageWidth = getIntent().getIntExtra("img-width", 0);
        imageHeight = getIntent().getIntExtra("img-height", 0);
        iRoot = findViewById(R.id.i_root);
        frameLayout = findViewById(R.id.frame);
        imageView = findViewById(R.id.img);
        cropView = findViewById(R.id.crop);

        getData();

//        imageView.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                rootWidth = iRoot.getWidth();
//                rootHeight = iRoot.getHeight();
//
//                float xScale = (float) rootWidth / imageWidth;
//                float yScale = (float) rootHeight / imageHeight;
//
//                //For Center Crop use the Math.max to calculate the scale
//                //float scale = Math.max(xScale, yScale);
//                //For Center Inside use the Math.min scale.
//                //I prefer Center Inside so I am using Math.min
//                scale = Math.min(xScale, yScale);
//
//                float scaledWidth = scale * imageWidth;
//                float scaledHeight = scale * imageHeight;
//
//                Log.i(TAG,"imageWidth=== "+imageWidth+" ,  imageHeight=== " + imageHeight);
//
//                //Set the new size for the VideoView based on the dimensions of the video
//                ViewGroup.LayoutParams layoutParams = frameLayout.getLayoutParams();
//                layoutParams.width = (int) scaledWidth;
//                layoutParams.height = (int) scaledHeight;
//                frameLayout.setLayoutParams(layoutParams);
//                frameLayout.invalidate(); //刷新界面
//
//                if (path != null && path.lastIndexOf(".") > 0) {
//                    Glide.with(RemoveWaterMarkActivity.this).load(new File(path)).into(imageView);
//                }
//
//                int xCenter = layoutParams.width/2;
//                int yCenter = layoutParams.height/2;
//                int initCropWidth = 400, intCropHeight = 200;
//                //cropView.setCropRect(new RectF(xCenter-initCropWidth/2, yCenter-intCropHeight/2, xCenter+initCropWidth/2, yCenter+intCropHeight/2));
//                cropView.setCropRect(new RectF(0, 0, layoutParams.width, layoutParams.height));
//
//
//            }
//        }, 100);

    }

    private String filePath;

    private void getData() {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels;
        imageHeight = metrics.heightPixels;

        filePath = getIntent().getStringExtra("path"); //图片原始路径
        loadImage(filePath);
    }


    /**
     * 异步载入编辑图片
     */
    private LoadImageTask mLoadImageTask;

    public void loadImage(String filepath) {
        if (mLoadImageTask != null) {
            mLoadImageTask.cancel(true);
        }
        mLoadImageTask = new LoadImageTask();
        mLoadImageTask.execute(filepath);
    }

    private int scaledw, scaledh;

    private final class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {  //设置显示在界面正中的图片的宽高，params[0]是图片路径
            Bitmap bitmap = BitmapUtils.getSampledBitmap(params[0], imageWidth,
                    imageHeight);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap newBit) { //参数是AsyncTask的第三个参数
            //将获得的bitmap存储起来
            //限定选中了多张图片时，存储bitmap
            //result为空。。。

            if (newBit == null) {//如果获取到的图片为空，返回
                return;
            } else {
                imageView.setImageBitmap(newBit);
                imageView.post(new Runnable() {
                    @Override
                    public void run() {
                        rootWidth = iRoot.getWidth();
                        rootHeight = iRoot.getHeight();
                        imageWidth = imageView.getWidth();
                        imageHeight = imageView.getHeight();
                        //使用glide获取图片宽高
                        Glide.with(RemoveWaterMark2Activity.this).asBitmap().load(filePath)
                                .listener(new RequestListener<Bitmap>() {
                                    @Override
                                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                                        return false;
                                    }

                                    @Override
                                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                                        return false;
                                    }
                                })
                                .into(new SimpleTarget<Bitmap>() {
                                    @Override
                                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                        int width = resource.getWidth();//图片原始宽度
                                        int height = resource.getHeight();//图片原始高度
                                        if (width > height) {
                                            scaledw = rootWidth;//固定图片展示高度为180dp
                                            scaledh = (height * scaledw) / width;//计算出按比缩放后的宽度
                                        } else {
                                            scaledh = rootHeight;//固定图片展示高度为180dp
                                            scaledw = (width * scaledh) / height;//计算出按比缩放后的宽度
                                            if (scaledw>rootWidth){
                                                //如果宽度超过了屏幕宽度，重新计算
                                                scaledw = rootWidth;
                                                scaledh = (height * scaledw) / width;//计算出按比缩放后的宽度
                                            }
                                        }

                                        float xScale = (float) rootWidth / width;
                                        float yScale = (float) rootHeight / height;


                                        scale = Math.min(xScale, yScale);

                                        Log.i(TAG, "scale==="+scale+"imageWidth=== " + imageWidth + " ,  imageHeight=== " + imageHeight);

                                        //Set the new size for the VideoView based on the dimensions of the video
                                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) frameLayout.getLayoutParams();
                                        layoutParams.width = (int) scaledw;
                                        layoutParams.height = (int) scaledh;
                                        frameLayout.setLayoutParams(layoutParams);
                                        frameLayout.invalidate(); //刷新界面

                                        cropView.setCropRect(new RectF(0, 0, layoutParams.width, layoutParams.height));
                                        Log.i(TAG, "Glide获取到的 rootWidth=== " + rootWidth + " ,  rootHeight=== " + rootHeight);
                                        Log.i(TAG, "Glide获取到的 width=== " + width + " ,  height=== " + height);
                                        Log.i(TAG, "Glide获取到的 scaledw=== " + scaledw + " ,  scaledh=== " + scaledh);
                                    }
                                });


                    }
                });


            }

        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.btn_save:

                //添加友盟事件统计
                MyUtils.addUmengEvent(RemoveWaterMark2Activity.this,"img_remove_water_save","图片去水印保存");
                save();
                break;
        }
    }

    private ProgressDialog mProgressDialog;
    public static final int MSG_SUCCESS = 1001;
    public static final int MSG_FAIL = 1002;
    public static final int MSG_PROGRESS = 1003;
    private static final int MSG_CANCLE = 1004;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_SUCCESS) {
                Log.i(TAG, "去水印完成，跳转");
                Toast.makeText(RemoveWaterMark2Activity.this, "处理完成", Toast.LENGTH_SHORT).show();
                MyArt art = new MyArt();
                art.setPath(outPath);
                art.setCreate_time(System.currentTimeMillis() + "");
                art.setWidth(imageWidth);
                art.setHeight(imageHeight);
                art.setType(0);
                art.save();
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
                Intent intent = new Intent(RemoveWaterMark2Activity.this, ShowMyArtsActivity.class);
                intent.putExtra(EXTRA_OUTPUT, art.getPath());
                intent.putExtra("create_time", art.getTrueCreateTime());
                intent.putExtra("width", imageHeight);
                intent.putExtra("height", imageWidth);
                intent.putExtra("type", "0");
                FileUtil.ablumUpdate(RemoveWaterMark2Activity.this, art.getPath(),0);//更新相册
                startActivity(intent);
                finish();

            } else if (msg.what == MSG_FAIL) {
                Toast.makeText(RemoveWaterMark2Activity.this, "处理失败", Toast.LENGTH_SHORT).show();
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
            } else if (msg.what == MSG_PROGRESS) {
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            } else if (msg.what == MSG_CANCLE) {
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            }
        }
    };


    private void save() {

        outPath = VideoUtil.VIDEO_SLIDE_IMAGE_DIR + "/" + System.currentTimeMillis() + ".png";
        RectF rect = cropView.getCropRect();

        String cmd = String.format("ffmpeg -i %s -filter_complex delogo=x=%d:y=%d:w=%d:h=%d:show=0 %s", path, (int) (rect.left / scale), (int) (rect.top / scale), (int) (rect.width() / scale), (int) (rect.height() / scale), outPath);
//        String cmd = String.format("ffmpeg -i %s -filter_complex delogo=x=%d:y=%d:w=%d:h=%d:show=0 %s", path, (int) (rect.left), (int) (rect.top), (int) (rect.width()), (int) (rect.height()), outPath);
        String[] commands = cmd.split(" ");
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setMax(100);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle("正在处理中");

        mProgressDialog.show();
        try {
            RxFFmpegInvoke.getInstance().runCommandRxJava(commands).subscribe(new RxFFmpegSubscriber() {
                @Override
                public void onFinish() {
                    Log.i(TAG, "EpEditor.execCmd onSuccess");
                    mHandler.sendEmptyMessage(MSG_SUCCESS);
                }

                @Override
                public void onProgress(int progress, long progressTime) {
                    Log.i(TAG, "EpEditor.execCmd onProgress " + progress);
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putFloat("progress", progress);
                    msg.setData(data);
                    msg.what = MSG_PROGRESS;
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onCancel() {
                    Log.i(TAG, "EpEditor.execCmd onFailure");
                    mHandler.sendEmptyMessage(MSG_CANCLE);
                }

                @Override
                public void onError(String message) {
                    Log.i(TAG, "EpEditor.execCmd onFailure");
                    mHandler.sendEmptyMessage(MSG_FAIL);
                }
            });
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            System.out.println(e);
            Toast.makeText(this, "保存出错", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("RemoveWaterMark2Activity");//统计页面
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("RemoveWaterMark2Activity");//统计页面
        MobclickAgent.onPause(this);
    }
}
